package cn.calm.database;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;

import cn.calm.database.dao.IDatabaseDao;
import cn.calm.database.dao.impl.DatabaseDaoImpl;
import cn.calm.database.entity.TableInfo;
import cn.calm.database.service.IDatabaseService;
import cn.calm.database.service.ITableInfoService;
import cn.calm.database.service.impl.DatabaseServiceImpl;
import cn.calm.database.service.impl.TableInfoServiceImpl;

@SuppressWarnings("rawtypes")
public class Activator implements BundleActivator {
	public BundleContext context;
	private EntityManagerFactory emf;
	private EntityManager em;

	private ServiceRegistration<IDatabaseService> registerDatabaseService;
	ServiceRegistration<ITableInfoService> registerTableInfoService;

	@Override
	public void start(BundleContext context) throws Exception {
		this.context = context;

		IDatabaseDao dao = new DatabaseDaoImpl();
		IDatabaseService<TableInfo> databaseService = new DatabaseServiceImpl<TableInfo>();
		emf = Persistence.createEntityManagerFactory("entity");
		em = emf.createEntityManager();
		dao.setSession(em);
		databaseService.setBaseDao(dao);

		registerDatabaseService = context.registerService(
				IDatabaseService.class, databaseService, null);

		TableInfoServiceImpl<TableInfo> service = new TableInfoServiceImpl<TableInfo>();
		databaseService.setBaseDao(dao);
		service.setDatabaseDao(dao);
		registerTableInfoService = context.registerService(
				ITableInfoService.class, service, null);
	}

	@Override
	public void stop(BundleContext arg0) throws Exception {
		if (em != null) {
			em.close();
		}
		if (emf != null) {
			emf.close();
		}
		if (registerDatabaseService != null) {
			registerDatabaseService.unregister();
		}
		if (registerTableInfoService != null) {
			registerTableInfoService.unregister();
		}
		context = null;
	}
}
